package com.aurora.listener;

import com.alibaba.fastjson.JSON;
import com.aurora.entity.ExceptionLog;
import com.aurora.entity.OperationLog;
import com.aurora.event.*;
import com.aurora.mapper.EsSchoolMapper;
import com.aurora.mapper.ExceptionLogMapper;
import com.aurora.mapper.OperationLogMapper;
import com.aurora.model.dto.EmailDTO;
import com.aurora.model.dto.UserInfoDTO;
import com.aurora.neo4j.dao.PersonRepository;
import com.aurora.neo4j.service.PersonService;
import com.aurora.service.OperationLogService;
import com.aurora.service.RedisService;
import com.aurora.service.UserInfoService;
import com.aurora.spider.gitee.ProductDetail;
import com.aurora.spider.houyuantuan.Person;
import com.aurora.spider.houyuantuan.PersonShip;
import com.aurora.util.EmailUtil;
import com.aurora.util.JGitUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static com.aurora.constant.CommonConstant.BLOGGER_ID;

@Component
@Log4j2
public class AuroraListener {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private ExceptionLogMapper exceptionLogMapper;


    @Autowired
    EsSchoolMapper esSchoolMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OperationLogService operationLogService;

    @Autowired
    RedisService redisService;

    @Value(value = "${spider.git_space}")
    String gitSpace;

    @Autowired
    PersonRepository personRepository;

    @Resource
    EmailUtil emailUtil;
    @Resource
    UserInfoService userInfoService;

    @Async
    @EventListener(OperationLogEvent.class)
    public void saveOperationLog(OperationLogEvent operationLogEvent) {
        operationLogMapper.insert((OperationLog) operationLogEvent.getSource());
    }

    @Async
    @EventListener(ExceptionLogEvent.class)
    public void saveExceptionLog(ExceptionLogEvent exceptionLogEvent) {
        ExceptionLog source = (ExceptionLog) exceptionLogEvent.getSource();
        exceptionLogMapper.insert(source);
        if (source.getUnknownException()) {
            //未知异常 发送邮件 即使处理
            sendExceptionEmail(source);
        }
    }

    @Async
    @EventListener(GiteeSpiderEvent.class)
    public void saveExceptionLog(GiteeSpiderEvent giteeSpiderEvent) {

        ProductDetail productDetail = (ProductDetail) giteeSpiderEvent.getSource();
        if (StringUtils.isNotBlank(productDetail.getGitUrl())) {
            //写入es
            esSchoolMapper.save(productDetail);
        }
        //拉取到本地
        //  pullGitee(productDetail);

        //todo 代码存于本地或者minio中
    }


    /**
     * 添加明星
     *
     * @param houyuantuanEvent
     */
    @Async
    @EventListener(HouyuantuanEvent.class)
    public void houyuantuanEvent(HouyuantuanEvent houyuantuanEvent) {
        Person person = (Person) houyuantuanEvent.getSource();
        //更新或保存信息
        personService.saveOrUpdate(person);

    }

    @Autowired
    PersonService personService;
    /**
     * 处理关系 以及添加不存在的朋友
     *
     * @param personShipEvent
     */
    @Async
    @EventListener(PersonShipEvent.class)
    public void personShipEvent(PersonShipEvent personShipEvent) {
        PersonShip personShip = (PersonShip) personShipEvent.getSource();
        personService.personShipEvent(personShip);


    }

    private void pullGitee(ProductDetail productDetail) {
        JGitUtil jGitUtil = new JGitUtil(productDetail.getProjectName(), productDetail.getGitUrl(), gitSpace);
        String result = jGitUtil.clone();

        //拉取后上传值minio TODO
        OperationLog operationLog = OperationLog.builder().build();
        operationLog.setOptModule("爬虫");
        operationLog.setOptType("拉取代码");
        operationLog.setOptDesc(productDetail.getProjectName() + ":" + productDetail.getAuther());
        operationLog.setRequestMethod("pull git");
        operationLog.setOptMethod("GiteeSpiderConsumer");
        operationLog.setRequestParam(JSON.toJSONString(productDetail));
        operationLog.setResponseData(result);
        operationLog.setUserId(1);
        operationLog.setNickname("系统爬虫");
        operationLog.setIpAddress("");
        operationLog.setIpSource("");
        operationLog.setOptUri("");
        operationLogService.save(operationLog);
    }

    private void sendExceptionEmail(ExceptionLog source) {
        EmailDTO emailDTO = new EmailDTO();
        Map<String, Object> map = new HashMap<>();
        UserInfoDTO userInfo = userInfoService.getUserInfoById(BLOGGER_ID);
        emailDTO.setEmail(userInfo.getEmail());
        emailDTO.setSubject("未知异常提醒");
        emailDTO.setTemplate("common.html");
        String url = "https://www.blog.jonk.top/auroradmin/#/login";
        map.put("content", "一只懒猫@博客【" + source.getOptDesc() + "】发生未知异常，"
                + "<a style=\"text-decoration:none;color:#12addb\" href=\"" + url + "  \">点击处理</a> <br/><br/>"
                + source.getExceptionInfo().substring(0, source.getExceptionInfo().indexOf("at"))
        );
        emailDTO.setCommentMap(map);
        emailUtil.sendHtmlMail(emailDTO);
    }

}
